//
//  JTStartViewController.m
//  IDLFaceSDKDemoOC
//
//  Created by 万事如意 on 2025/9/1.
//  Copyright © 2025 Baidu. All rights reserved.
//

#import "JTStartViewController.h"
#import "UIView+Tool.h"
#import "BDFaceAgreementViewController.h"
#import "BDFaceLogoView.h"
#import <objc/runtime.h>
#import "JSToastDialogs.h"
#import "BDFacePoorNetworkController.h"
#import "BDFaceVerificationFailController.h"
#import "BDUIConstant.h"
#import "BDFaceVerificationConstant.h"
#import "JTStartViewController+Step.h"
#import "JTStartViewController+LiveCheck.h"
#import "FaceParameterConfig.h"
#import "BDFaceAdjustParamsTool.h"
#import "JTFaceImageAttendenceManager.h"
#import "AudioManager.h"
#import "GCDAsyncUdpSocket.h"

@interface JTStartViewController () <GCDAsyncUdpSocketDelegate>
{
    NSDateFormatter *formatter;
    BOOL isBindUDP;
}

@property (nonatomic, strong) UILabel *placeNameLa, *empNameLa, *departmenLa, *timeLa, *statusLa;

@property (nonatomic, strong) GCDAsyncUdpSocket *sendSocket;

@end

@implementation JTStartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.viewModel = [[AttendenceViewModel alloc] init];
    formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [self initView];
    if (AdminInfo.shareInfo.placeKey.length) {
        [self dealAttendenceTokenWithType:1];
        [self initFaceServiceAndInfoCollectService];
    }
    //测试时打开
//    [self dealAttendenceTokenWithType:1];
    __block JTStartViewController * blockSelf = self;
    //plus执行打卡结果返回以及pro获取考勤信息失败返回
    self.viewModel.attendentBlock = ^(BOOL isSuccess, NSString * _Nonnull msg) {
        if (isSuccess) {
            NSDictionary *dict = [JTFaceImageAttendenceManager sharedInstance].lastEmpModel;
            blockSelf.empNameLa.text = [NSString stringWithFormat:@"姓名:%@",dict[@"empName"]];
            blockSelf.departmenLa.text = [NSString stringWithFormat:@"部门:%@",dict[@"empDepartmentName"]];
            
            blockSelf.timeLa.text = [NSString stringWithFormat:@"时间:%@",[blockSelf->formatter stringFromDate:[NSDate date]]];
            [blockSelf setStatusText:msg status:YES];
            [[AudioManager shareInstance] attendenceSuccess];
        } else {
            
            blockSelf.empNameLa.text = [NSString stringWithFormat:@"姓名:%@",@""];
            blockSelf.departmenLa.text = [NSString stringWithFormat:@"部门:%@",@""];
            blockSelf.timeLa.text = [NSString stringWithFormat:@"时间:%@",@""];
            [[AudioManager shareInstance] attendenceFailuer];
            [blockSelf setStatusText:msg status:NO];
        }
    };
    
    //pro 执行打卡
    self.viewModel.udpResultBlock = ^(NSDictionary * _Nonnull result) {
        [blockSelf udpRequestWithDict:result];
    };
}

- (void)udpRequestWithDict:(NSDictionary *)data {
    uint16_t port = [[data objectForKey:@"port"] intValue];
    NSString *post = [data objectForKey:@"host"];
    NSString *content = [data objectForKey:@"content"];
    
    if (!isBindUDP) {
        NSError *error = nil;
        self.sendSocket.delegate = self;
        [self.sendSocket bindToPort:port error:&error];
        if (error == nil) {
            [self.sendSocket beginReceiving:nil];
            [self.sendSocket sendData:[content dataUsingEncoding:NSUTF8StringEncoding] toHost:post port:port withTimeout:5 tag:0];
            isBindUDP = YES;
        } else {
            [self setStatusText:error.localizedDescription status:NO];
            isBindUDP = NO;
        }
    } else {
        [self.sendSocket sendData:[content dataUsingEncoding:NSUTF8StringEncoding] toHost:post port:port withTimeout:5 tag:0];
    }
}

- (void)initView {
    
    CGFloat rectWidth = kScreenWidth*0.625;//480//kScreenWidth*0.625
    CGFloat rectHeight = 596*rectWidth/480.0;
    CGRect rectFrame = CGRectMake((kScreenWidth-rectWidth)/2, 40, rectWidth, rectHeight);
    
    UIView *maskView = [[UIView alloc] initWithFrame:APPWINDOW.bounds];
    [maskView gradualChangeColorViewWithColors:@[HEX_COLOR(@"#15151D"),HEX_COLOR(@"#262634")]];
    [self.view addSubview:maskView];
    UIBezierPath *bp = [UIBezierPath bezierPathWithRoundedRect:APPWINDOW.bounds cornerRadius:0];
    [bp appendPath:[UIBezierPath bezierPathWithRect:rectFrame]];
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = bp.CGPath;
    layer.fillRule = kCAFillRuleEvenOdd;
    maskView.layer.mask = layer;
    
    CGFloat pluginValue = 20;
    CGRect borderRect = CGRectMake(rectFrame.origin.x-pluginValue, rectFrame.origin.y-pluginValue, rectFrame.size.width+pluginValue*2, rectFrame.size.height+pluginValue*2);
    UIImageView *imgv = [[UIImageView alloc] initWithFrame:borderRect];
    imgv.backgroundColor = [UIColor clearColor];
    imgv.image = [UIImage imageNamed:@"scanRect"];
    imgv.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imgv];
    
    UIButton *tapScanBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    tapScanBtn.backgroundColor = HEX_ThemeColor;
    tapScanBtn.layer.cornerRadius = 75;
    tapScanBtn.titleLabel.font = [UIFont boldSystemFontOfSize:30];
    [tapScanBtn setTitle:@"点击考勤" forState:UIControlStateNormal];
    [tapScanBtn setTintColor:HEX_COLOR(@"#ffffff")];
    tapScanBtn.center = imgv.center;
    [tapScanBtn addTarget:self action:@selector(tapScanClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:tapScanBtn];
    
    
    UIImageView *bottomLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, kScreenHeight-43-56, kScreenWidth, 43)];
    bottomLine.image = [UIImage imageNamed:@"bottomLine"];
    bottomLine.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:bottomLine];
    
    self.placeNameLa = [[UILabel alloc] initWithFrame:bottomLine.frame];
    self.placeNameLa.textColor = HEX_COLOR(@"#ffffff");
    self.placeNameLa.font = [UIFont systemFontOfSize:20];
    self.placeNameLa.textAlignment = NSTextAlignmentCenter;
    self.placeNameLa.text = [AdminInfo shareInfo].placeName;
    [self.view addSubview:self.placeNameLa];
    
    UIImageView *infoV = [[UIImageView alloc] initWithFrame:CGRectMake(borderRect.origin.x, CGRectGetMaxY(borderRect)+37, borderRect.size.width, 216)];//empInfobg
    infoV.image = [UIImage imageNamed:@"empInfobg"];
    infoV.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:infoV];
    
    self.empNameLa = [[UILabel alloc] initWithFrame:CGRectMake(66, 61, borderRect.size.width/2, 25)];
    self.empNameLa.textColor = HEX_COLOR(@"#ffffff");
    self.empNameLa.text = @"姓名：";
    self.empNameLa.font = [UIFont boldSystemFontOfSize:16];
    [infoV addSubview:self.empNameLa];
    self.departmenLa = [[UILabel alloc] initWithFrame:CGRectMake(66, CGRectGetMaxY(self.empNameLa.frame)+10, borderRect.size.width/2, 25)];
    self.departmenLa.textColor = HEX_COLOR(@"#ffffff");
    self.departmenLa.text = @"部门：";
    self.departmenLa.font = [UIFont boldSystemFontOfSize:16];
    [infoV addSubview:self.departmenLa];
    self.timeLa = [[UILabel alloc] initWithFrame:CGRectMake(66, CGRectGetMaxY(self.departmenLa.frame)+10, borderRect.size.width/2, 25)];
    self.timeLa.textColor = HEX_COLOR(@"#ffffff");
    self.timeLa.font = [UIFont boldSystemFontOfSize:16];
    self.timeLa.text = @"考勤时间：";
    [infoV addSubview:self.timeLa];
    
    self.statusLa = [UILabel new];
    self.statusLa.frame = CGRectMake(66, CGRectGetMaxY(self.timeLa.frame)+5, borderRect.size.width*2/3, 40);
    self.statusLa.numberOfLines = 2;
    self.statusLa.font = [UIFont boldSystemFontOfSize:16];
    self.statusLa.adjustsFontSizeToFitWidth = YES;
    [infoV addSubview:self.statusLa];
    
    UILabel *deviceID = [[UILabel alloc] initWithFrame:CGRectMake(0, kScreenHeight-56, kScreenWidth, 56)];
    deviceID.textColor = HEX_COLOR(@"#ffffff");
    deviceID.font = [UIFont boldSystemFontOfSize:14];
    deviceID.textAlignment = NSTextAlignmentCenter;
    deviceID.text = [NSString stringWithFormat:@"设备号：%@",[UUIDManager getUUID]];
    deviceID.userInteractionEnabled = YES;
    [deviceID addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(copyUDID)]];
    [self.view addSubview:deviceID];
    
    [[NSUserDefaults standardUserDefaults] setInteger: 3 forKey:@"AirInterface"];
}

- (void)setStatusText:(NSString *)msg status:(BOOL)sucess {
    if (sucess) {
        self.statusLa.text = [NSString stringWithFormat:@"%@",msg];
        self.statusLa.textColor = HEX_COLOR(@"#bef467");
    } else {
        self.statusLa.text = [NSString stringWithFormat:@"%@",msg];
        self.statusLa.textColor = HEX_COLOR(@"#e4240c");
    }
}

//type：1 获取access_token, 2 获取 verify_token
- (void)dealAttendenceTokenWithType:(int)tockenType {
    //设备ID
    NSString *udid =[UUIDManager getUUID];
    NSDictionary *dict = @{@"deviceId":udid,@"type":@(tockenType)};
    if (tockenType == 2) {
        dict = @{@"deviceId":udid,@"type":@(tockenType),@"planId":@"24272"};
    }
    NSMutableArray *marr = [NSMutableArray array];
    for (NSString *key in dict.allKeys) {
        [marr addObject:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
    }
    NSString *bodyStr = [marr componentsJoinedByString:@"&"];
    DLog(@"%@",bodyStr);
    NSURL *url = [NSURL URLWithString:@"https://cloud.hzjtyh.com/api/pc/home/getBaiduFaceAttendanceToken"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    configuration.timeoutIntervalForRequest = 30;
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSMutableDictionary *responseDic = [NSJSONSerialization JSONObjectWithData: data
                                                                               options: NSJSONReadingMutableContainers
                                                                                 error: &error];
            dispatch_async(dispatch_get_main_queue(), ^{
                DLog(@"%@",responseDic);
                NSDictionary *dict = (NSDictionary *)responseDic;
                NSNumber *code = (NSNumber *)[dict objectForKey:@"error_code"];
                NSString *msg = (NSString *)[dict objectForKey:@"msg"];
                NSDictionary *dataDict = (NSDictionary *)[dict objectForKey:@"data"];
                [self.activityIndicator stopAnimating];
                if ([code isEqualToNumber:@0]) {
                    if (tockenType == 2) {
                        if (dataDict[@"verify_token"]) {
                            NSString *token = dataDict[@"verify_token"];
                            self.verifyToken = token;
                            AdminInfo.shareInfo.verifyToken = token;
                            [self.activityIndicator stopAnimating];
                            [BDFaceBaseKitManager sharedInstance].paramsCustomConfigItem.recordAbility = YES;
                            if ([AdminInfo.shareInfo.enableLiveness isEqualToString:@"1"]) {
                                [self startLiveCheck];
                            } else {
                                [self startCheck];
                            }
                        } else {
                            [BDFaceToastView showToast:APPWINDOW text: msg];
                        }
                    } else {
                        if (dataDict[@"access_token"]) {
                            //获取token
                            NSString *token = dataDict[@"access_token"];
                            self.accessToken = token;
                            AdminInfo.shareInfo.accessToken = token;
                        } else {
                            [BDFaceToastView showToast:APPWINDOW text: msg];
                        }
                        
                    }
                }
            });
        } else {
            [self.activityIndicator stopAnimating];
            [BDFaceToastView showToast:APPWINDOW text: error.localizedDescription];
        }
    }];
    [task resume];
}

- (void)copyUDID {
    UIPasteboard *board = [UIPasteboard generalPasteboard];
    [board setString:[UUIDManager getUUID]];
    [BDFaceToastView showToast:APPWINDOW text:@"已复制"];
}

- (void)tapScanClicked {
    //    [self getVerifyToeken];
    if (AdminInfo.shareInfo.placeKey.length > 0) {
        [self dealAttendenceTokenWithType:2];
    } else {
        [BDFaceToastView showToast:APPWINDOW text: @"场所信息未能获取，请配置后重启"];
    }
    //测试时打开
//    [self dealAttendenceTokenWithType:2];
}

#pragma mark GCDAsyncSocketDelegate

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext {
    NSString *contentStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:[contentStr componentsSeparatedByString:@"#"]];
    [arr removeObject:@""];
    if (arr.count) {
        NSString *code = [NSString stringWithFormat:@"%@",arr[0]];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([code isEqualToString:@"00000"]) {
                NSDictionary *mo = @{
                    @"empName":arr[1],
                    @"empDepartmentName":arr[2]
                };
                [JTFaceImageAttendenceManager sharedInstance].lastEmpModel = mo;
                self.empNameLa.text = [NSString stringWithFormat:@"姓名:%@",arr[1]];
                self.departmenLa.text = [NSString stringWithFormat:@"部门:%@",arr[2]];
                
                self.timeLa.text = [NSString stringWithFormat:@"时间:%@",[self->formatter stringFromDate:[NSDate date]]];
                [self setStatusText:arr.lastObject status:YES];
                [[AudioManager shareInstance] attendenceSuccess];
            } else {
                if (arr.count > 2 ) {
                    NSDictionary *mo = @{
                        @"empName":arr[1],
                        @"empDepartmentName":arr[2]
                    };
                    
                    [JTFaceImageAttendenceManager sharedInstance].lastEmpModel = mo;
                    self.empNameLa.text = [NSString stringWithFormat:@"姓名:%@",arr[1]];
                    self.departmenLa.text = [NSString stringWithFormat:@"部门:%@",arr[2]];
                    self.timeLa.text = [NSString stringWithFormat:@"时间:%@",[self->formatter stringFromDate:[NSDate date]]];
                } else {
                    self.empNameLa.text = [NSString stringWithFormat:@"姓名:%@",@""];
                    self.departmenLa.text = [NSString stringWithFormat:@"部门:%@",@""];
                    self.timeLa.text = [NSString stringWithFormat:@"时间:%@",@""];
                }
                [self setStatusText:arr.lastObject status:NO];
                [[AudioManager shareInstance] attendenceFailuer];
            }
        });
    } else {
        [self setStatusText:@"已识别人脸，但未能返回考勤信息" status:NO];
        [[AudioManager shareInstance] attendenceFailuer];
    }
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setStatusText:@"打卡信息已发送，请等待结果" status:NO];
    });
}

- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError  * _Nullable)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setStatusText:@"UDP连接已关闭，请联系管理员" status:NO];
    });
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError * _Nullable)error {
    [self setStatusText:error.localizedDescription status:NO];
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setStatusText:@"UDP服务器已连接" status:YES];
    });
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError * _Nullable)error {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setStatusText:error.localizedDescription status:YES];
    });
}

- (GCDAsyncUdpSocket *)sendSocket {
    if (!_sendSocket) {
        _sendSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];//dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    }
    return _sendSocket;
}

@end
